<template>
  <section class="todoapp">
    <!-- 头部部分 -->
    <TodoHeader @addName="addName" />
    <!-- 主体部分 -->
    <TodoMain :list="showList" @doDel="doDel" @changeDone="changeDone" @isAllCheck="isAllCheck" />
    <!-- 底部部分 -->
    <TodoFooter :list="showList" @clearName="clearName" @getType="getType" />
  </section>
</template>

<script>
import TodoFooter from "./components/TodoFooter.vue";
import TodoHeader from "./components/TodoHeader.vue";
import TodoMain from "./components/TodoMain.vue";
export default {
  components: { TodoFooter, TodoHeader, TodoMain },
  data() {
    return {
      type: 'all',
      list: JSON.parse(localStorage.getItem('list')||'[]')
    };
  },
  methods: {
    doDel(id) {
      const index = this.list.findIndex((item) => item.id === id);
      this.list.splice(index, 1);
    },
    changeDone(id) {
      const obj = this.list.find((item) => item.id === id);
      obj.isDone = !obj.isDone;
    },
    addName(name) {
      this.list.push({
        name,
        id: Date.now(),
        isDone: false,
      });
    },
    clearName() {
      this.list = this.list.filter((item) => !item.isDone);
    },
    getType(type) {
      this.type = type;
    },
    isAllCheck(val){
      this.list.forEach(item=>item.isDone=val)
    }
  },
  computed: {
    showList() {
      if (this.type === "all") {
        return this.list;
      } else if (this.type === "active") {
        return this.list.filter((item) => !item.isDone);
      } else {
        return this.list.filter((item) => item.isDone);
      }
    },
  },
  watch:{
    list:{
      deep:true,
      handler(){
        localStorage.setItem('list',JSON.stringify(this.list))
      }
    }
  }
};
</script>

<style></style>
